package com.tanhua.listener;

import com.tanhua.domain.PublishScore;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;

@Component
@RocketMQMessageListener(
        topic = "tanhua-bigdata",
        consumerGroup = "tanhua-bigdata-c")
public class PublishScoreListener implements RocketMQListener<Map> {


    @Autowired
    private MongoTemplate mongoTemplate;

    //创建监听器 从消息中间件中获取数据
    @Override
    public void onMessage(Map map) {

        long userId = Long.parseLong(map.get("userId").toString());
        long pid = Long.parseLong(map.get("pid").toString());
        int type = Integer.parseInt(map.get("type").toString());

        //封装数据
        PublishScore publishScore = new PublishScore();
        publishScore.setId(new ObjectId());
        publishScore.setDate(new Date().getTime());
        publishScore.setPublishId(pid);//大数据需要的id
        publishScore.setUserId(userId);

        //设置初始分数
        Double score = 0D;
        /*- 操作1： 浏览 +1
        - 操作2： 点赞 +5
        - 操作3： 喜欢 +8
        - 操作4： 评论 + 10
        - 操作5：取消点赞 -5
        - 操作6：取消喜欢 -8*/

        switch (type) {
            case 1: {
                score = 1d;
                break;
            }case 2:{
                score = 5D;
                break;
            }case 3:{
                score = 8D;
                break;
            }case 4:{
                score = 10D;
                break;
            }case 5:{
                score = -5D;
                break;
            }case 6:{
                score = -8D;
                break;
            }default:{
                break;
            }
        }
        publishScore.setScore(score);

        //历史行为数据保存到mangodb中去
        mongoTemplate.save(publishScore);
        System.out.println("用户行为数据统计得分: "+score);

    }
}
